package dataStructureAlgorithms;

/**
 * @Description: TODO 二分查找 针对有序数组
 * @Author: wzj
 * @Date: 2019/10/6 8:52
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr=new int[]{1,3,5,7,9,11,13,15,16,17,19,20};
        System.out.println(binarySearch(arr,6));
    }

    /**
     * 返回要查找的值在数组中的下标
     * @param arr 升序
     * @param value
     * @return
     */
    public static int binarySearch(int[] arr,int value){
        int low=0,high=arr.length-1,middle=(low+high)/2;
        while(true){
            if(low>high){
                return -1;
            }
            if(arr[middle]==value){
                return middle;
            } else {
                if(arr[middle]>value){
                    high=middle-1;
                } else {
                    low=middle+1;
                }
                middle=(low+high)/2;
            }
        }
    }
}
